package com.example.demo;

import com.example.demo.mapper.UserMapper;
import com.example.demo.utils.ExcuteLinux;
import com.example.demo.utils.ValidatorUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
@Component
public class FileListener extends FileAlterationListenerAdaptor {

    //private  static FileCopy fileCopy;
    public static String source ;
    //目标路径
    public static String target ;
    //执行linux命令
    private ExcuteLinux excuteLinux;
    //打包输出文件
    private FileToJar fileToJar;
    //文件名校验
    private ValidatorUtil validatorUtil;
    @Resource
    UserMapper userMapper;

    public FileListener(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    /**
     * 文件创建执行
     */
    @SneakyThrows
    @Override
    public void onFileCreate(File file) {
        log.info("[new]:" + file.getPath());
        System.out.println(file.getName());
        //运行仿真前的准备
//        if (file.getName().equals("c_11_tsm_cty")) {
//            //可执行文件的根目录
//            String target = file.getParentFile().getAbsolutePath();
////            Clone(inputfilesSource, target);
//            System.out.println("输入文件导入成功");
//            excuteLinux.exeCmd("./c_11_tsm_cty");
//        }else {
//            System.out.println("请上传可执行文件");
//        }
    }
            //shell执行超时时间
//            final int SHELL_TIME_OUT = 10;
//            Scanner input = new Scanner(System.in);
//            String result = "";
//            Process process = null;
//            try {
//                process = Runtime.getRuntime().exec("./c_11_tsm_cty");
                // 等待命令执行完成
//                process.waitFor(SHELL_TIME_OUT, TimeUnit.SECONDS);
//                OutputStream outputStream = process.getOutputStream();
//                InputStream is = process.getInputStream();
//                input = new Scanner(is);
//                while (input.hasNextLine()) {
//                    result += input.nextLine() + "\n";
//                }
//            } catch (InterruptedException | IOException e) {
//                e.printStackTrace();
//            } finally {
//                if (null != input) {
//                    input.close();
//                }
//                if (null != process) {
//                    process.destroy();
//                }
//            }
            //Process listen = Runtime.getRuntime().exec("cmd /c start " + listener);     //
//        } else {
//            System.out.println("未加载可执行文件");
//        }
//    }
//        if(file.getName().equals("progress.txt")){
//
//            //获取文件的上级目录名
//            String strParentDirectory = file.getParentFile().getName();
//            //System.out.println("PATH : " + strParentDirectory);
//            System.out.println("PATH : " + strParentDirectory);
//
//            //获取name和time
//            String name = strParentDirectory.substring(0,strParentDirectory.length()-16);
//            System.out.println(name);
//            String time = strParentDirectory.substring(strParentDirectory.length()-15,strParentDirectory.length());
//            System.out.println(time);


            //读取文件内容并写入数据库
//            BufferedReader buf = null;
//            try {
//                buf = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
//                BufferedReader br = new BufferedReader(buf);
//                //System.out.println(br.readLine());
//                String data = br.readLine();
//
//                float progress = Float.valueOf(data);
//                System.out.println(progress);
//
//                //修改数据库
//                Integer id = userMapper.findIdByName(name,time);
//                System.out.println(id);
//                User user = userMapper.findByName(name,time);
//                System.out.println(user);
//                user.setId(id);
//                user.setProgress(progress);
//                System.out.println(user);
//                userMapper.updateProById(user);
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//                try {if (buf != null){buf.close();}}catch (Exception e){}
//            }
//        }
//        else if(file.getName().equals("2.xml")){
//
//            String dirName = file.getParentFile().getName();
//            String target = file.getParentFile().getAbsolutePath();
//            //写脚本文件
//            String callon = "cd test" + "\n" + "cd " + dirName + "\n" + "start fileWatcher.exe" +"\n" + "start ChinaUnionCellCreatorProject.exe" + "\n" + "EXIT";
//
//            try{
//                //创建可执行程序
//                File batFile = new File(target + "/callon.bat");
//                if(batFile.createNewFile()) {
//                    System.out.println("文件创建成功！");
//                    BufferedWriter out = new BufferedWriter(
//                            new OutputStreamWriter(new FileOutputStream(batFile,true)));
//                    out.write(callon+"\n");
//                    out.close();
//                }
//                else
//                    System.out.println("出错了，该文件已经存在");
//            }
//            catch(IOException ioe) {
//                ioe.printStackTrace();
//            }
//
//            //调用程序
//            String startup = target + "\\callon.bat";
//
//            try {
//                Process start = Runtime.getRuntime().exec("cmd /c start " + startup);       //
//                //Process listen = Runtime.getRuntime().exec("cmd /c start " + listener);     //
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            System.out.println("是xml");
//        }

    /**
     * 文件创建修改
     */
    @Override
    public void onFileChange(File file) {
        log.info("[update]:" + file.getAbsolutePath());

        System.out.println(file.getName());
//        if(file.getName().equals("progress.txt")){
//            //获取文件的上级目录名
//            String strParentDirectory = file.getParentFile().getName();
//            //System.out.println("PATH : " + strParentDirectory);
//            System.out.println("PATH : " + strParentDirectory);
//
//            //获取name和time
//            String name = strParentDirectory.substring(0,strParentDirectory.length()-16);
//            System.out.println(name);
//            String time = strParentDirectory.substring(strParentDirectory.length()-15,strParentDirectory.length());
//            System.out.println(time);
//
//            //读取文件内容并写入数据库
//            BufferedReader buf = null;
//            try {
//                buf = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
//                BufferedReader br = new BufferedReader(buf);
//                //System.out.println(br.readLine());
//                String data = br.readLine();
//                float progress = Float.valueOf(data);
//                System.out.println(progress);
//                //进度拉满
//                if(Math.abs(progress-100.0)<=0)
//                {
//                    source =  file.getParentFile().getAbsolutePath() + "\\save";
//                    target = "D:\\Desktop\\test\\demo6\\data\\" + file.getParentFile().getName();
//                    //System.out.println(dirName);
//
//                    // System.out.println(target);
//
//                    //复制文件到新建文件夹
//                    long startTime = System.currentTimeMillis();
//                    Clone(source,target);
//                    long endTime = System.currentTimeMillis();
//                    //System.out.println("总共用时："+(endTime-startTime));
//
//                    Path path= Paths.get(file.getParentFile().getAbsolutePath());
//                    //删除之前的文件夹
//                    boolean root = deleteDirectory(path);
//
//                    //压缩文件夹
//                    String sourceFilePath = "D:\\Desktop\\test\\demo6\\data\\" + file.getParentFile().getName();
//                    String zipFilePath = "D:\\Desktop\\test\\demo6\\data\\" + file.getParentFile().getName();
//                    String fileName = file.getParentFile().getName();
//
//                    FileToZip.fileToZip(sourceFilePath, zipFilePath,fileName);
//
//                }
//
//                //修改数据库
//                Integer id = userMapper.findIdByName(name,time);
//                System.out.println(id);
//                User user = userMapper.findByName(name,time);
//                //System.out.println(id);
//                System.out.println(user);
//                user.setId(id);
//                user.setProgress(progress);
//                System.out.println(user);
//                userMapper.updateProById(user);
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//                try {if (buf != null){buf.close();}}catch (Exception e){}
//            }
//        }
//        else if(file.getName().equals("2.xml")){
//            System.out.println("是xml");
//        }
    }
//13109102178

//    public User findById(@PathVariable("id") Long id) {
//        return userMapper.findById(id);
//    }
    /**
     * 文件删除
     */
    @Override
    public void onFileDelete(File file) {
        log.info("[delete]:" + file.getAbsolutePath());
    }

    /**
     * 目录创建
     */
    @Override
    public void onDirectoryCreate(File directory) {
        log.info("[new]:" + directory.getAbsolutePath());
//        source = "/home/lenovo/java/Sub6G/inputfiles/inputfiles";
        source = "/home/unicom/tongyijiemian/java_sub6G/Sub6G/inputfiles/inputfiles";
//        String mergeSource = "/home/lenovo/java/Sub6G/inputfiles/merge";
        String mergeSource = "/home/unicom/tongyijiemian/java_sub6G/Sub6G/inputfiles/merge";
//        String dataTarget = "/home/lenovo/java/Sub6G/sim_data";
        String dataTarget = "/home/unicom/tongyijiemian/java_sub6G/Sub6G/sim_data";
        target = directory.getAbsolutePath();

        String parentDir = directory.getParentFile().getName();
        String dirName = directory.getName();
        System.out.println(target);
        System.out.println(dirName);

        if(validatorUtil.isValid(dirName)){
            //复制文件到新建文件夹
            long startTime = System.currentTimeMillis();
            excuteLinux.exeCmd("cp -a "+source+" "+target);
            excuteLinux.exeCmd("cp -a "+mergeSource+" "+target);
            long endTime = System.currentTimeMillis();
            System.out.println("总共用时："+(endTime-startTime));
        }else if(dirName.equals("inputfiles")){
            System.out.println("输入文件导入成功");
            System.out.println("开始仿真");
//            excuteLinux.exeCmdSim("cd /home/lenovo/java/Sub6G/"+parentDir+" && ./merge > process.txt",parentDir,directory,dataTarget);

            excuteLinux.exeCmdSim("cd /home/unicom/tongyijiemian/java_sub6G/Sub6G/"+parentDir+" && chmod 777 merge && ./merge > process.txt",parentDir,directory,dataTarget);

            //            System.out.println("仿真成功");
//            StreamGobble zipStream = excuteLinux.exeCmdStream("cd /home/lenovo/java/data"+"/"+parentDir +" && "+"zip -r "+parentDir+".zip"+" "+"outputfiles",simStream);
//            System.out.println(parentDir+"输出数据压缩完成");
//            StreamGobble copyStream = excuteLinux.exeCmdStream("cp -a "+directory.getParentFile()+"/"+parentDir+".zip"+" "+dataTarget,zipStream);
        }
//        if(dirName.equals("wbc")) {
//            //复制文件到新建文件夹
//            long startTime = System.currentTimeMillis();
//            excuteLinux.exeCmd("cp -a "+source+" "+target);
//            excuteLinux.exeCmd("cp -a "+mergeSource+" "+target);
//            long endTime = System.currentTimeMillis();
//            System.out.println("总共用时："+(endTime-startTime));
//        }
//        if(dirName.equals("aabc")) {
//            //复制文件到新建文件夹
//            long startTime = System.currentTimeMillis();
//            excuteLinux.exeCmd("cp -a "+source+" "+target);
//            excuteLinux.exeCmd("cp -a "+mergeSource+" "+target);
//            long endTime = System.currentTimeMillis();
//            System.out.println("总共用时："+(endTime-startTime));
//        }
//        if(dirName.equals("outputfiles")){
//            //压缩输出文件
//            excuteLinux.exeCmd("cd /home/lenovo/java/data"+"/"+parentDir +" && "+"zip -r "+parentDir+".zip"+" "+dirName);
//            System.out.println(parentDir+"输出数据压缩完成");
//            excuteLinux.exeCmd("cp -a "+directory.getParentFile()+"/"+parentDir+".zip"+" "+dataTarget);
//        }
    }

    /**]
     * 目录修改
     */
    @Override
    public void onDirectoryChange(File directory) {
//        String dataTarget = "/home/lenovo/java/Sub6G/sim_data";
        String dataTarget = "/home/unicom/tongyijiemian/java_sub6G/Sub6G/sim_data";
        log.info("[update]:" + directory.getAbsolutePath());
//        String parentDir = directory.getParentFile().getName();
//        String taskDir = directory.getParentFile().getParentFile().getName();
//        if(parentDir.equals("outputfiles")){
//            System.out.println(taskDir+":仿真结束");
////            excuteLinux.exeCmd("cd /home/lenovo/java/Sub6G"+"/"+taskDir +" && "+"zip -r "+taskDir+".zip"+" "+"outputfiles");
//            excuteLinux.exeCmd("cd /home/unicom/tongyijiemian/java_sub6G/Sub6G"+"/"+taskDir +" && "+"zip -r "+taskDir+".zip"+" "+"outputfiles");
//            System.out.println(taskDir+":输出数据压缩完成");
////            Clone(directory.getParentFile().getParentFile()+"/"+taskDir+".zip",dataTarget);
//            excuteLinux.exeCmd("cp -a "+directory.getParentFile().getParentFile()+"/"+taskDir+".zip"+" "+dataTarget);
//        }

    }

    /**
     * 目录删除
     */
    @Override
    public void onDirectoryDelete(File directory) {
        log.info("[delete]:" + directory.getAbsolutePath());
    }

    @Override
    public void onStart(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStart(observer);
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStop(observer);
    }

//    @param sourse
//    @param target
    //复制文件
    public static void Clone(String source,String target){
        //获取目录下所有文件
        File f = new File(source);
        File[] allf = f.listFiles();

        System.out.println(source);
        System.out.println(target);

        //遍历所有文件
        for(File fi:allf) {
            try {
                //拼接目标位置
                String URL = target+fi.getAbsolutePath().substring(source.length());

                //创建目录或文件
                if(fi.isDirectory()) {
                    Createflies(URL);
                }else {
                    fileInputOutput(fi.getAbsolutePath(),URL);
                }

                //递归调用
                if(fi.isDirectory()) {
                    Clone(fi.getAbsolutePath(),URL);
                }

            }catch (Exception e) {
                System.out.println("error");
            }
        }
    }

    /**
     * 复制文件
     * @param source
     * @param target
     */
    public static void fileInputOutput(String source,String target) {
        try {
            File s = new File(source);
            File t = new File(target);

            FileInputStream fin = new FileInputStream(s);
            FileOutputStream fout = new FileOutputStream(t);

            byte[] a = new byte[1024*1024*4];
            int b = -1;

            //边读边写
            while((b = fin.read(a))!=-1) {
                fout.write(a,0,b);
            }

            fout.close();
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     * @param name
     * @return
     */
    public static boolean Createflies(String name) {
        boolean flag=false;
        File file=new File(name);
        //创建目录
        if(file.mkdir() == true){
            System.out.println("Success！");
            flag=true;
        }else {
            System.out.println("Fail！");
            flag=false;

        }

        return flag;
    }

    //删除文件夹
    public static boolean deleteDirectory(Path path) {
        if (Files.isDirectory(path)) {
            try {
                FileUtils.deleteDirectory(path.toFile());
                return true;
            } catch (IOException e) {
                e.getMessage();
            }
        }

        return false;
    }

}
